// 全局错误处理中间件
const errorHandler = (err, req, res, next) => {
  console.error('错误：', err);

  // 默认错误响应
  const response = {
    message: '服务器内部错误',
    error_code: 'INTERNAL_SERVER_ERROR'
  };

  // 根据错误类型设置适当的状态码和响应
  if (err.name === 'ValidationError') {
    res.status(422);
    response.message = '数据验证失败';
    response.error_code = 'VALIDATION_ERROR';
    response.errors = err.errors;
  } else if (err.name === 'UnauthorizedError') {
    res.status(401);
    response.message = '未授权访问';
    response.error_code = 'UNAUTHORIZED';
  } else if (err.name === 'ForbiddenError') {
    res.status(403);
    response.message = '禁止访问';
    response.error_code = 'FORBIDDEN';
  } else if (err.name === 'NotFoundError') {
    res.status(404);
    response.message = '资源未找到';
    response.error_code = 'NOT_FOUND';
  } else {
    // 默认使用500状态码
    res.status(500);
  }

  // 在开发环境下返回错误堆栈信息
  if (process.env.NODE_ENV === 'development') {
    response.stack = err.stack;
  }

  res.json(response);
};

// 自定义错误类
class ValidationError extends Error {
  constructor(message, errors = {}) {
    super(message);
    this.name = 'ValidationError';
    this.errors = errors;
  }
}

class UnauthorizedError extends Error {
  constructor(message = '未授权访问') {
    super(message);
    this.name = 'UnauthorizedError';
  }
}

class ForbiddenError extends Error {
  constructor(message = '禁止访问') {
    super(message);
    this.name = 'ForbiddenError';
  }
}

class NotFoundError extends Error {
  constructor(message = '资源未找到') {
    super(message);
    this.name = 'NotFoundError';
  }
}

// 新增 AppError 类
class AppError extends Error {
  constructor(message, statusCode) {
    super(message);
    this.statusCode = statusCode;
    this.name = 'AppError'; // 或者 this.constructor.name;
    this.isOperational = true; 
    Error.captureStackTrace(this, this.constructor);
  }
}

module.exports = {
  errorHandler,
  AppError, // 添加 AppError 到导出
  ValidationError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError
}; 